package org.tloss.web.editor.database.editors;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.SQLException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.tloss.web.editor.Utils;
import org.tloss.web.editor.model.Database;

public class DatabaseEditor extends EditorPart implements
		IResourceChangeListener {
	Database database = null;

	public Database getDatabase() {
		return database;
	}

	private boolean dirty = false;
	TreeViewer treeViewer;

	public void doSave(IProgressMonitor monitor) {
		IEditorInput editorInput = this.getEditorInput();
		IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
		IFile file = fileEditorInput.getFile();
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Database.class);
			Marshaller marshaller = context.createMarshaller();
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			marshaller.marshal(database, arrayOutputStream);

			file.setContents(
					new ByteArrayInputStream(arrayOutputStream.toByteArray()),
					false, true, monitor);
			this.dirty = false;
			this.firePropertyChange(IEditorPart.PROP_DIRTY);
		} catch (JAXBException e) {
			Utils.logError("Can't save database", e);
		} catch (CoreException e) {
			Utils.logError("Can't save database", e);

		}

	}

	public void doSaveAs() {

	}

	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		if (!(input instanceof IFileEditorInput)) {
			throw new PartInitException("Input must be a file");
		}
		setSite(site);
		setInput(input);
		IFileEditorInput editorInput = (IFileEditorInput) input;
		IFile file = editorInput.getFile();
		JAXBContext context;
		InputStream inputStream = null;
		try {
			inputStream = file.getContents();
			if (inputStream.available() == 0) {
				database = new Database();
				database.setOffineModde(true);
			} else {
				context = JAXBContext.newInstance(Database.class);
				Unmarshaller marshaller = context.createUnmarshaller();
				database = (Database) marshaller.unmarshal(inputStream);

			}
		} catch (CoreException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		} catch (JAXBException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		} catch (IOException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				Utils.logError("Can't close input stream", e);
			}
		}
	}

	public boolean isDirty() {

		return dirty;
	}

	public boolean isSaveAsAllowed() {

		return false;
	}

	public void createPartControl(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		layout.numColumns = 2;

		Composite treeContainer = new Composite(composite, SWT.BORDER);
		GridData gridData = new GridData();
		treeContainer.setLayoutData(gridData);
		gridData.horizontalAlignment = SWT.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = SWT.FILL;
		gridData.grabExcessVerticalSpace = true;
		TreeColumnLayout treeLayout = new TreeColumnLayout();
		treeContainer.setLayout(treeLayout);
		treeViewer = new TreeViewer(treeContainer, SWT.MULTI
				| SWT.FULL_SELECTION);
		Tree tree = treeViewer.getTree();
		tree.setHeaderVisible(true);
		TreeColumn keyColumn;
		TreeColumn valueColumn;

		keyColumn = new TreeColumn(tree, SWT.NONE);
		keyColumn.setText("Name");
		treeLayout.setColumnData(keyColumn, new ColumnWeightData(2));

		valueColumn = new TreeColumn(tree, SWT.NONE);
		valueColumn.setText("Value");
		treeLayout.setColumnData(valueColumn, new ColumnWeightData(2));

		treeViewer.setContentProvider(new DatabaseConfigContentProvider(
				database));
		final DatabaseConfigLableProvider treeLabelProvider = new DatabaseConfigLableProvider();
		treeViewer.setLabelProvider(treeLabelProvider);

		TreeViewerColumn column1 = new TreeViewerColumn(treeViewer, keyColumn);

		column1.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return treeLabelProvider.getColumnText(element, 0);
			}

			public Image getImage(Object element) {

				return treeLabelProvider.getImage(element);
			}
		});

		TreeViewerColumn column2 = new TreeViewerColumn(treeViewer, valueColumn);
		column2.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return treeLabelProvider.getColumnText(element, 1);
			}

			public Image getImage(Object element) {

				return treeLabelProvider.getImage(element);
			}
		});

		column2.setEditingSupport(new EditingSupport(treeViewer) {

			TextCellEditor editor = new TextCellEditor((Composite) treeViewer
					.getControl());
			ComboBoxCellEditor checkboxCellEditor = new ComboBoxCellEditor(
					(Composite) treeViewer.getControl(), new String[] {
							"false", "true" });

			DialogCellEditor libEditor = new DialogCellEditor(
					(Composite) treeViewer.getControl()) {

				@Override
				protected Object openDialogBox(Control cellEditorWindow) {
					FileDialog dlg = new FileDialog(
							cellEditorWindow.getShell(), SWT.OPEN);
					dlg.setText("Open");

					dlg.setFilterNames(new String[] { "Jar/Zip file" });
					dlg.setFilterExtensions(new String[] { "*.jar;*.zip" });
					String path = dlg.open();
					if (path == null)
						return "";
					return path;
				}
			};

			protected boolean canEdit(Object element) {
				return true;
			}

			protected CellEditor getCellEditor(Object element) {
				if (element instanceof DatabaseConfig) {
					DatabaseConfig config = (DatabaseConfig) element;
					if (DatabaseConfig.JDBCLIB.equals(config.getName())) {
						return libEditor;
					} else if (DatabaseConfig.ONFFLINE_MODE.equals(config
							.getName())) {
						return checkboxCellEditor;
					}
				}
				return editor;
			}

			protected Object getValue(Object element) {
				if (element instanceof DatabaseConfig) {
					DatabaseConfig field = ((DatabaseConfig) element);
					return field.getValue();
				}
				return treeLabelProvider.getColumnText(element, 1);
			}

			protected void setValue(Object element, Object value) {

				Object text = value;
				if (element instanceof DatabaseConfig) {
					DatabaseConfig field = ((DatabaseConfig) element);
					if (field.getValue() != null || text != null) {
						if ((text != null && !text.equals(field.getValue()))
								|| (field.getValue() != null && !field
										.getValue().equals(text))) {

							field.setValue(text);
							treeModified(element);
						}
					}
				}

			}

			private void treeModified(Object element) {
				treeViewer.refresh(element);
				dirty = true;
				firePropertyChange(IEditorPart.PROP_DIRTY);
			}
		});

		getSite().setSelectionProvider(treeViewer);

		treeViewer.setInput(database);

		treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);

		Composite wrapper = new Composite(composite, SWT.NONE);
		RowLayout rowLayout = new RowLayout();
		wrapper.setLayout(rowLayout);
		rowLayout.type = SWT.VERTICAL;

		final Button button = new Button(wrapper, SWT.NONE);
		button.setText("Test connection");

		button.addMouseListener(new MouseListener() {

			public void mouseUp(MouseEvent e) {

			}

			public void mouseDown(MouseEvent e) {
				URL jarUrl;
				StringBuffer buffer = new StringBuffer();
				boolean connected = false;
				try {
					jarUrl = new URL("jar", "", "file:"
							+ new File(database.getJdbcLib()).getAbsolutePath()
							+ "!/");
					URLClassLoader classLoader = new URLClassLoader(
							new URL[] { jarUrl }, this.getClass()
									.getClassLoader());

					DatabaseConnect connect = new DatabaseConnect(database
							.getJdbcURL(), database.getJdbcUsername(), database
							.getJdbcPassword(), database.getDriverClass(),
							classLoader);
					Connection connection = connect.getConnection();
					if (connection != null) {
						connected = true;
						MessageBox messageBox = new MessageBox(button
								.getShell(), SWT.OK);
						messageBox.setMessage("Connection is success");
						messageBox.open();
					}
				} catch (MalformedURLException e1) {
					Utils.logError("Fail to connect to database", e1);
					buffer.append(e1.getMessage());
				} catch (SQLException e1) {
					Utils.logError("Fail to connect to database", e1);
					buffer.append(e1.getMessage());
				} catch (ClassNotFoundException e1) {
					Utils.logError("Fail to connect to database", e1);
					buffer.append(e1.getMessage());
				} catch (InstantiationException e1) {
					Utils.logError("Fail to connect to database", e1);
					buffer.append(e1.getMessage());
				} catch (IllegalAccessException e1) {
					Utils.logError("Fail to connect to database", e1);
					buffer.append(e1.getMessage());
				}
				if (!connected) {
					MessageBox messageBox = new MessageBox(button.getShell(),
							SWT.OK);
					messageBox.setMessage("Connection is fail. "
							+ buffer.toString());
					messageBox.open();
				}
			}

			public void mouseDoubleClick(MouseEvent e) {

			}
		});
	}

	public void setFocus() {

	}

	@Override
	public void resourceChanged(IResourceChangeEvent arg0) {
		dirty = true;
		firePropertyChange(IEditorPart.PROP_DIRTY);
	}

}
